<template>
  <div class="admin-container">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="header-content">
        <!-- 左侧logo -->
        <div class="logo-section">
          <div class="logo">
            <el-icon size="28" color="#409EFF">
              <Setting />
            </el-icon>
            <span class="logo-text">集大校友平台 - 后台管理</span>
          </div>
        </div>

        <!-- 右侧管理员信息 -->
        <div class="header-right">
          <div class="user-section">
            <el-dropdown @command="handleAdminCommand">
              <div class="user-info">
                <span class="user-email">{{ adminEmail }}</span>
                <el-avatar :size="32" :src="adminAvatar" class="user-avatar">
                  {{ adminEmail.charAt(0).toUpperCase() }}
                </el-avatar>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">
                    <el-icon>
                      <User />
                    </el-icon>
                    管理员资料
                  </el-dropdown-item>
                  <el-dropdown-item command="settings">
                    <el-icon>
                      <Setting />
                    </el-icon>
                    修改密码
                  </el-dropdown-item>
                  <el-dropdown-item divided command="back">
                    <el-icon>
                      <Back />
                    </el-icon>
                    返回前台
                  </el-dropdown-item>
                  <el-dropdown-item divided command="logout">
                    <el-icon>
                      <SwitchButton />
                    </el-icon>
                    退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>
    </header>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 左侧边栏 -->
      <aside class="sidebar">
        <div class="sidebar-content">
          <!-- 管理导航 -->
          <div class="admin-nav">
            <h3 class="sidebar-title">管理导航</h3>
            <el-menu :default-active="activeSidebar" class="sidebar-menu" router @select="handleSidebarSelect">
              <el-menu-item index="/admin/dashboard">
                <el-icon>
                  <DataAnalysis />
                </el-icon>
                <span>数据概览</span>
              </el-menu-item>
              <el-menu-item index="/admin/user-manage">
                <el-icon>
                  <User />
                </el-icon>
                <span>用户管理</span>
              </el-menu-item>
              <el-menu-item index="/admin/user-verify">
                <el-icon>
                  <DocumentChecked />
                </el-icon>
                <span>校友管理</span>
              </el-menu-item>
              <el-menu-item index="/admin/post-manage">
                <el-icon>
                  <Document />
                </el-icon>
                <span>动态管理</span>
              </el-menu-item>
              <el-menu-item index="/admin/circle-manage">
                <el-icon>
                  <Collection />
                </el-icon>
                <span>圈子管理</span>
              </el-menu-item>
              <el-menu-item index="/admin/job-manage">
                <el-icon>
                  <Opportunity />
                </el-icon>
                <span>招聘信息管理</span>
              </el-menu-item>
              <el-menu-item index="/admin/job-application-audit">
                <el-icon>
                  <Finished />
                </el-icon>
                <span>求职申请审核</span>
              </el-menu-item>
              <el-menu-item index="/admin/market-manage">
                <el-icon>
                  <Goods />
                </el-icon>
                <span>订单管理</span>
              </el-menu-item>
              <el-menu-item index="/admin/lostfound-manage">
                <el-icon>
                  <Box />
                </el-icon>
                <span>失物招领管理</span>
              </el-menu-item>
              <el-menu-item index="/admin/system-config">
                <el-icon>
                  <Tools />
                </el-icon>
                <span>系统配置</span>
              </el-menu-item>
              <el-menu-item index="/admin/admin-manage">
                <el-icon>
                  <User />
                </el-icon>
                <span>管理员管理</span>
              </el-menu-item>
              <el-menu-item index="/admin/announcement-manage">
                <el-icon>
                  <ChatDotRound />
                </el-icon>
                <span>公告管理</span>
              </el-menu-item>
              <el-menu-item index="/admin/banner-manage">
                <el-icon>
                  <Picture />
                </el-icon>
                <span>轮播图管理</span>
              </el-menu-item>
            </el-menu>
          </div>
        </div>
      </aside>

      <!-- 修改密码对话框 -->
      <el-dialog v-model="changePasswordDialogVisible" title="修改密码" width="400px" destroy-on-close>
        <el-form ref="changePasswordFormRef" :model="changePasswordForm" :rules="changePasswordRules"
          label-width="100px">
          <el-form-item label="旧密码" prop="oldPassword">
            <el-input v-model="changePasswordForm.oldPassword" type="password" placeholder="请输入旧密码" show-password />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="changePasswordForm.newPassword" type="password" placeholder="请输入新密码" show-password />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="changePasswordForm.confirmPassword" type="password" placeholder="请确认新密码" show-password />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="changePasswordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleChangePasswordSubmit" :loading="changePasswordLoading">
            确定
          </el-button>
        </template>
      </el-dialog>

      <!-- 右侧内容区域 -->
      <main class="content">
        <div class="content-wrapper">
          <!-- 路由视图 -->
          <router-view></router-view>
        </div>
      </main>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
  Setting, User, SwitchButton, Back,
  DataAnalysis, DocumentChecked, Document, Collection,
  Opportunity, Tools,
  ChatDotRound, Box
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAdminStore } from '@/stores/admin'
import { changeAdminPassword } from '@/api/admin'
import { sha1 } from 'js-sha1'

const router = useRouter()
const route = useRoute()
const adminStore = useAdminStore()

// 响应式数据
const adminEmail = computed(() => adminStore.getAdminName() || adminStore.getAdminEmail())
const adminAvatar = ref('')

// 修改密码相关
const changePasswordDialogVisible = ref(false)
const changePasswordLoading = ref(false)
const changePasswordFormRef = ref()

// 修改密码表单
const changePasswordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 修改密码验证规则
const changePasswordRules = {
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value === changePasswordForm.oldPassword) {
          callback(new Error('新密码不能与旧密码相同'))
        } else {
          callback()
        }
      }, trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== changePasswordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      }, trigger: 'blur'
    }
  ]
}

// 计算当前激活的菜单项
const activeSidebar = computed(() => {
  return route.path
})

// 方法定义
const handleSidebarSelect = (index) => {
  console.log('导航到:', index)
}

const handleAdminCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/admin/profile')
      break
    case 'settings':
      // 打开修改密码对话框
      changePasswordDialogVisible.value = true
      resetChangePasswordForm()
      break
    case 'back':
      router.push('/')
      break
    case 'logout':
      handleLogout()
      break
  }
}

// 提交修改密码
const handleChangePasswordSubmit = async () => {
  if (!changePasswordFormRef.value) return

  try {
    await changePasswordFormRef.value.validate()
    changePasswordLoading.value = true

    const response = await changeAdminPassword({
      oldPassword: sha1(changePasswordForm.oldPassword),
      newPassword: sha1(changePasswordForm.newPassword)
    })

    if (response.code === 0) {
      ElMessage.success('修改密码成功')
      changePasswordDialogVisible.value = false
      resetChangePasswordForm()
    } else {
      ElMessage.error(response.msg || '修改密码失败')
    }
  } catch (error) {
    if (error.errors) {
      ElMessage.error('请完善表单信息')
    } else {
      ElMessage.error('修改密码失败')
      console.error('修改密码失败:', error)
    }
  } finally {
    changePasswordLoading.value = false
  }
}

// 重置修改密码表单
const resetChangePasswordForm = () => {
  Object.keys(changePasswordForm).forEach(key => {
    changePasswordForm[key] = ''
  })

  if (changePasswordFormRef.value) {
    changePasswordFormRef.value.clearValidate()
  }
}

const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await adminStore.adminLogout()
    ElMessage.success('已退出登录')
    // 强制跳转到管理员登录页
    router.push('/admin/login')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('退出失败:', error)
      // 即使失败也清除数据并跳转
      adminStore.clearAdminData()
      router.push('/admin/login')
    }
  }
}

onMounted(() => {
  // 检查管理员登录状态
  if (!adminStore.isAdminLoggedIn()) {
    console.log('管理员未登录，跳转到登录页')
    router.push('/admin/login')
    return
  }

  // 验证 token 是否有效
  console.log('当前管理员token:', adminStore.adminToken)
  console.log('当前管理员信息:', adminStore.adminInfo)
})
</script>

<style scoped>
.admin-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

/* 头部样式 */
.header {
  background: #ffffff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 1000;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  height: 64px;
}

.logo-section {
  display: flex;
  align-items: center;
}

.logo {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
}

.logo-text {
  font-size: 18px;
  font-weight: 600;
}

.header-right {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 6px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: #f5f7fa;
}

.user-email {
  font-size: 14px;
  color: #606266;
}

/* 侧边栏样式 */
.sidebar {
  width: 280px;
  background: #ffffff;
  box-shadow: 2px 0 8px 0 rgba(29, 35, 41, 0.05);
  overflow-y: auto;
}

.sidebar-content {
  padding: 20px 0;
}

.sidebar-title {
  font-size: 14px;
  color: #8c8c8c;
  margin: 0 20px 12px;
  font-weight: 500;
}

.sidebar-menu {
  border-right: none;
}

.sidebar-menu .el-menu-item {
  height: 48px;
  line-height: 48px;
  margin: 0 12px;
  border-radius: 6px;
}

.sidebar-menu .el-menu-item.is-active {
  background-color: #ecf5ff;
}

.badge {
  margin-left: auto;
}

/* 快捷操作 */
.action-list {
  padding: 0 20px;
}

.action-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.action-item:hover {
  background-color: #f5f7fa;
}

.action-text {
  font-size: 14px;
  color: #303133;
}

/* 系统状态 */
.status-list {
  padding: 0 20px;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.status-item:last-child {
  border-bottom: none;
}

.status-label {
  font-size: 14px;
  color: #606266;
}

/* 内容区域样式 */
.content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

.content-wrapper {
  height: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    padding: 0 16px;
  }

  .sidebar {
    width: 240px;
  }
}
</style>